﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.Commands;
using Ncqrs;
using Ncqrs.Commanding.ServiceModel;
using ReadModel;

namespace Website.Controllers
{
    public class HomeController : Controller
    {
        EFReadContext _context = new EFReadContext();
        ICommandService _service;

        public HomeController()
        {
            _service = NcqrsEnvironment.Get<ICommandService>();
        }

        [HttpGet]
        public ActionResult Index()
        {
            var model = _context.NoteListItems.OrderByDescending(x=>x.Importance).ToList();
            return View(model);
        }

        public ActionResult Details(Guid noteId)
        {
            var model = _context.NoteDetails.FirstOrDefault(x => x.NoteId == noteId);
            return View(model);
        }

        [HttpGet]
        public ActionResult CreateNote()
        {
            var model = new CreateNoteCommand();
            model.NoteId = Guid.NewGuid();
            return View(model);
        }

        [HttpPost]
        public ActionResult CreateNote(CreateNoteCommand command)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _service.Execute(command);
                    return View("Success");
                }
                catch { return View(command); }
            }

            return View(command);
        }

        [HttpGet]
        public ActionResult ChangeImportance(Guid noteId)
        {
            var model = new ChangeImportanceCommand();
            model.NoteId = noteId;
            return View(model);
        }

        [HttpPost]
        public ActionResult ChangeImportance(ChangeImportanceCommand command)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _service.Execute(command);
                    return View("Success");
                }
                catch { return View(command); }
            }

            return View(command);
        }
    }
}
